<?php


namespace App\Service\VendorClient\ShopdamugeApi;


use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;

class ShopdamugeApiClient extends BaseService
{
    protected $clientConfig;

    /**
     * 初始参数
     * @param array $apiBody
     */
    public function __construct($apiBody = [])
    {
        $this->clientConfig = $apiBody;
    }

    public function queryGoodsList($params=[])
    {
        $data = [
//            'goodsno' => '',
//            'goodsname' => '',
        ];
        
        if ($params['page']==2){
            return Normal::returnCode(
                Normal::SUC,
                '获取成功', ['data'=>[]]
            );
        }
        
        $requestParam = [
            'method' => 'queryGoods',
            'requestMethod' => 'get',
            'data' => $data,
        ];
        $res=$this->execute($requestParam);
        if ($res['code']!=Normal::SUC){
            return $res;
        }
        //调用库存接口获取库存
        $stocks=$this->queryStock();
        if($stocks['code']!=Normal::SUC){
            return $stocks;
        }
        $stocks=array_column($stocks['data']['data'],NULL,'defaultcode');
        foreach ($res['data']['data'] as &$item){
            $item['stock']= $stocks[$item['defaultCode']] ?? [];
            unset($item);
        }
        return $res;
    }
    
    public function queryStock()
    {
        $requestParam = [
            'method' => 'queryStock',
            'requestMethod' => 'get',
            'data' =>[],
        ];
        return $this->execute($requestParam);
    }

    /**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        $orderInfo      = $params['supplierOrder'];
        $orderItem      = $params['orderGoods'];
        $order          = $params['order'];

        //支付流水号
        $pay_sn    = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //支付时间
        $pay_time   = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //支付流水号
        $order_sn       = $orderInfo['supplier_dsn'];

        //判断支付方式是否存在
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);

        //组装商品数据列表
        $goodsList          = [];
        $goodsTotalMoney    = 0;
        $way_tax_fee        = 0;
        foreach ($orderItem as $key =>  & $item )
        {
            $tax_rate           = bcadd('1', (string)$item['tax_rate'],4);
            $price              = $item['price'];
            $spec_num           = $item['spec_num'];
            $quantity           = $item['quantity'];
            $singlePrice        = bcdiv((string)$price, (string)$spec_num,3);

            //不含税价格
            $goodsPrice         = bcdiv((string)$price, $tax_rate,3);
            $goodsPrice         = bcdiv((string)$goodsPrice, (string)$spec_num,3);
            $goodsPrice         = bcmul((string)$goodsPrice,(string)100,1);
            $goodsPrice         = bcdiv((string)ceil($goodsPrice), 100,2);


            $buyNum             = $spec_num * $quantity;
            $goodsTotalPrice    = bcmul((string)$goodsPrice,(string)$buyNum,2);

            //商品关税当前币种最小单位（分）
            $goodsCustomsTax    = bcsub((string)$singlePrice,(string)$goodsPrice,2);
            $taxAll             = bcmul($goodsCustomsTax,(string)$buyNum,2);

            $goodsInfo = [
                "defaultcode"           => $item['supplier_skucode'],
                "price"                 => (string)$goodsPrice,
                "sku"                   => $item['supplier_store_code'],
                "qty"                   => $buyNum,
            ];
            $goodsList[] = $goodsInfo;
            $goodsTotalMoney    = bcadd((string)$goodsTotalMoney,$goodsTotalPrice,2);
            $way_tax_fee        = bcadd((string)$way_tax_fee,$taxAll,2);
        }

        //订单总价（商品保税价格 + 运费）
        $totalMoney             = bcadd((string)$goodsTotalMoney, (string)$deliver_money,2);
        $totalMoney             = bcadd($totalMoney, (string)$way_tax_fee,2);
        //订单优惠金额
        $real_total_money       = $orderInfo['real_total_money'];
        $discount_money         = bcsub((string)$totalMoney,(string)$real_total_money,2);
        $currentGoods           = current($orderItem);
        //仓库ID
        $warehouse_id           = $currentGoods['supplier_store_id'];
        //创建订单数据
        $data=[
            'acturalpaid'                => $real_total_money,
            'batchnumbers'               => $order_sn,//批次号
            'buyeridnumber'              => $orderInfo['buyer_idcard'],
            'buyername'                  => $orderInfo['buyer_realname'],
            'buyerregno'                 => $orderInfo['buyer_realname'],
            'childid'                    => $this->clientConfig['childid'],
            'consignee'                  => $orderInfo['receive_name'],
            'consigneeaddress'           => $orderInfo['receive_address'],
            'consigneecity'              => $orderInfo['city'],
            'consigneecompany'           => '',
            'consigneeemail'             => '',
            'consigneeidcard'            => $orderInfo['buyer_idcard'],
            'consigneeprovince'          => $orderInfo['province'],
            'consigneestreet'            => $orderInfo['district'],
            'consigneetelephone'         => $orderInfo['recveive_phone'],
            'discount'                   => $discount_money,
            'ebpcode'                    => $order['enterpriseNum']??$apply_extends['enterpriseNum']??'',
            'ebpname'                    => $order['enterpriseName']??$apply_extends['enterpriseName']??'',
            'expressid'                  => $this->clientConfig['expressid'],
            'freight'                    => $orderInfo['deliver_money'],
            'items'                      => $goodsList,
            'note'                       => $orderInfo['order_remark'],
            'orderno'                    => $order_sn,
            'paycode'                    => $order['payCommanyCode']??$apply_extends['payCommanyCode']??'',
            'payname'                    => $order['payCommanyName']??$apply_extends['payCommanyName']??'',
            'paytransactionid'           => $pay_sn,
            'purchasertelephone'         => $orderInfo['buyer_phone'],
            'storeid'                    => $warehouse_id,
            'taxtotal'                   => $way_tax_fee
        ];
        
        $requestParam = [
            'method'    => 'OrderCreate',
            'requestMethod' => 'post',
            'data'      => $data,
        ];
        return $this->execute($requestParam);
    }

    /**
     * 获取发货物流信息
     */
    public function queryOrderExpress( $param = [] )
    {
        $data = [
            "orderno"  => $param['supplier_dsn'],
        ];
        $requestParam = [
            'method'    => 'queryExpress',
            'requestMethod' => 'get',
            'data'      => $data,
        ];
        return $this->execute($requestParam);
    }

    /**
     * 取消订单
     */
    public function cancelOrder( $params = [] )
    {
        $data = [
            'orderId'         => $params['supplierOrder']['supplier_dsn'],
        ];
        $requestParam = [
            'method'    => 'orderCancel',
            'requestMethod' => 'get',
            'data'      => $data,
        ];
        return $this->execute($requestParam);
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute($params = [])
    {
        $method         = $params['method'];
        $requestMethod  = $params['requestMethod'];
        $data           = $params['data'];
        $authData = [
            'apptoken' => $this->clientConfig['apptoken'],
            'appkey' => $this->clientConfig['appkey']
        ];
        $url = $this->clientConfig['baseurl'] . $this->clientConfig[$method];
        if ($requestMethod == 'get') {
            $url.='?'.http_build_query(array_merge($authData,$data));
        }else{
            $url.='?'.http_build_query($authData);
        }
        $parameter = [
            [
                'tag' => 'Shopdamuge_' . $method,
                'uid' => IdService::instance()->getOtherID(),
                'url' => $url,
                'data' => $data,
                'method' => $requestMethod,
                'format' => 'json',
                'header' => [],
            ],
        ];
        if( in_array($params['method'],['queryGoods','queryStock']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask  = current($resTask);
        $httpCode = $resTask['response']['httpCode'];
        $resHttp = @json_decode($resTask['response']['result'], true);
        $errorMsg = $resHttp['desc'] ?? $resHttp['error'] ?? '请求失败';
        if ($httpCode==Normal::SUC && $resHttp['result'] == "00") {
            return Normal::returnCode(Normal::SUC, "操作成功", $resHttp);
        }
        return Normal::returnCode(Normal::FAIL, $errorMsg);
    }


}
